# 异常
try:
    f = open('test.txt', 'r')
    print(f'这个没有异常')
    pass
except:
    f = open('test.txt', 'w')
    print('有异常')

print('-----------------异常 多个异常---------------')
# 2
num = 0
try:
    print(num)
    1 / 0
    pass
except (NameError, ZeroDivisionError):
    print('error')

print('-----------------异常 as e ,else,finally---------------')
try:
    print(num)
    # 1 / 0
    pass
except Exception as e:
    print(e)
    pass
else:
    # 没有异常执行的代码
    print('我是else,没有异常的时候执行的代码')
finally:
    print('这是最终要执行的')

print('-----------------异常传递---------------')
# 1. 尝试只读⽅式打开test.txt⽂件，如果⽂件存在则读取⽂件内容，⽂件不存在则提示⽤户即可。
# 2. 读取内容要求：尝试循环读取内容，读取过程中如果检测到⽤户意外终⽌程序，则 except 捕获异常
# 并提示⽤户。
import time

try:
    f = open('test.txt', 'r')
    # 读取文件
    try:
        while True:
            str = f.readline()
            if len(str) == 0:
                break
                pass
            print(str)
            # time.sleep(2)
            pass

        pass

    except:
        print('读取过程中意外终止')
        pass
    finally:

        f.close()
        pass
    pass
except:
    print('文件不存在')
    pass
finally:
    pass

print('-----------------自定义异常---------------')


class MyException(Exception):
    def __int__(self, length):
        self.length = length
        pass

    def __str__(self):
        print(f'异常为密码长度过短,密码长度:{self.length}')
        pass

    pass


def main():
    try:
        str = '123'
        if len(str) < 6:
            raise MyException(len(str))
        pass
    except Exception as e:
        print(e)
        pass
    finally:
        pass
    

    pass


main()
